package com.situ.web.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/servletContext3")
public class ServletContextServlet3 extends HttpServlet{

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 统计这个Servlet一共被所有用户访问了多少次
		ServletContext servletContext = getServletContext();
		// getAttribute返回的是Object类，返回值最好也用包装数据类型
		Integer count = (Integer)servletContext.getAttribute("count");
		System.out.println(count);
		// 如果count是null，这是第一次访问这个Servlet
		if (count == null) {
			count = 1;
		} else {
			count++;
		}
		servletContext.setAttribute("count", count);
		
		// 给浏览器返回一句话：这个Servlet被访问的次数：30
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter writer = resp.getWriter();
		writer.println("这个Servlet被访问的次数：" + count);
		writer.close();
	}
	
	
	
}
